<template>
  <div>

    <div>
      <!-- 筛选搜索标题 -->
      <el-card class="box-card" style="height: auto">
        <div class="title-content" style="margin-top: 20px;">
          <i class="el-icon-search"></i>
          <span>筛选搜索</span>
        </div>
        <!-- 筛选表单区域 -->
        <div class="search-form-container">
          <div>
            <el-form :inline="true" :model="orderRefundDTO" ref="orderRefundDTOForm" class="demo-form-inline">
              <!-- 表单项：订单号 -->
              <el-form-item label="订单号" prop="orderNo">
                <el-input
                  size="small"
                  v-model="orderRefundDTO.orderNo"
                  placeholder="请输入订单号"
                ></el-input>
              </el-form-item>

              <!-- 表单项：用户名 -->
              <el-form-item label="收货人" prop="username">
                <el-input
                  size="small"
                  v-model="orderRefundDTO.username"
                  placeholder="请输入用户名"
                ></el-input>
              </el-form-item>

              <!-- 表单项：申请时间 -->
              <el-form-item label="申请时间" prop="createdAt">
                <el-date-picker
                  v-model="orderRefundDTO.createdAt"
                  type="datetime"
                  placeholder="选择申请时间"
                  style="width: 100%"
                ></el-date-picker>
              </el-form-item>

              <!-- 表单项：退款状态 -->
              <el-form-item label="退款状态" prop="status">
                <el-select
                  size="small"
                  v-model="orderRefundDTO.status"
                >
                  <el-option label="待审核" value="0"></el-option>
                  <el-option label="退款中" value="1"></el-option>
                  <el-option label="退款成功" value="2"></el-option>
                  <el-option label="拒绝" value="3"></el-option>
                </el-select>
              </el-form-item>

              <!-- 按钮区域 -->
              <el-form-item class="button-group" style="margin-top: 0px; margin-bottom: 0px;">
                <el-button
                  type="success"
                  round
                  size="small"
                  @click="onSearch"
                  icon="el-icon-search"
                >
                  查询
                </el-button>
                <el-button
                  type="warning"
                  round
                  size="small"
                  @click="resetOrderRefundDTOForm('orderRefundDTOForm')"
                  icon="el-icon-refresh-left"
                >
                  重置
                </el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </el-card>


      <!-- 添加和批量删除按钮 -->
      <el-card style="height: 70px; width: 100%; margin-top: 5px; margin-bottom: 5px;">
        <div class="button-container" style="margin-left: 950px; margin-top: 0px;">
          <el-button class="btn_add" type="primary" @click="handleAddOrderRefund" size="middle" icon="el-icon-plus" style="margin: auto 10px 0px;">新增
          </el-button>
          <el-button class="btb_del" type="danger" @click="deleteOrderRefundBatch" size="middle" icon="el-icon-delete" style="margin: 0px auto;">
            批量删除
          </el-button>
        </div>
      </el-card>

      <el-dialog
        title="添加退款记录"
        :visible.sync="editDialogVisible"
        width="40%"
        :close-on-click-modal="false"
      >
        <el-form ref="orderRefundForm" :model="orderRefund" :rules="rules" label-width="100px">
          <el-form-item label="订单号" prop="orderNo">
            <el-input v-model="orderRefund.orderNo"></el-input>
          </el-form-item>
          <el-form-item label="收货人" prop="username">
            <el-input v-model="orderRefund.username"></el-input>
          </el-form-item>
          <el-form-item label="退款总金额" prop="refundAmount">
            <el-input v-model.number="orderRefund.refundAmount"></el-input>
          </el-form-item>
          <el-form-item label="退款原因" prop="reason">
            <el-input v-model="orderRefund.reason"></el-input>
          </el-form-item>
          <el-form-item label="退款状态" prop="status">
            <el-select v-model="orderRefund.status">
              <el-option label="待审核" value="0"></el-option>
              <el-option label="退款中" value="1"></el-option>
              <el-option label="退款成功" value="2"></el-option>
              <el-option label="拒绝" value="3"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="申请时间" prop="createdAt">
            <el-date-picker
              v-model="orderRefund.createdAt"
              type="date"
              placeholder="选择申请时间"
              style="width: 100%"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="处理时间" prop="refundAt">
            <el-date-picker
              v-model="orderRefund.refundAt"
              type="date"
              placeholder="选择处理时间"
              style="width: 100%"
            ></el-date-picker>
          </el-form-item>
        </el-form>

        <div slot="footer" class="dialog-footer" style="width: 200px; margin: 0 auto;">
          <el-button @click="resetOrderRefundDTOForm('orderRefundForm')">取 消</el-button>
          <el-button type="primary" @click="saveOrderRefund('orderRefundForm')">确 定</el-button>
        </div>
      </el-dialog>

      <!-- 表格 -->
      <div>
        <div class="title-content" style="margin-left: 20px; margin-top: 20px;">
          <i class="el-icon-menu"></i>
          <span>数据列表</span>
        </div>
        <div style="margin-top: 20px;">
          <el-table
            :data="tableData"
            border
            class="orderRefund-table"
            style="width: 100%"
            row-key="id"
            default-expand-all
            height="500"
            stripe
            :header-cell-style="{ background: '#f5f7fa', color: '#333', fontWeight: 'bold', textAlign: 'center' }"
            :cell-style="{ textAlign: 'center' }"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="id" label="退单编号" width="50px"></el-table-column>
            <el-table-column prop="order.orderNo" label="订单号" width="150px"></el-table-column>
            <el-table-column prop="user.username" label="收货人" width="130px"></el-table-column>
            <!-- 展示申请时间 -->
            <el-table-column prop="createdAt" label="申请时间" width="150px"></el-table-column>
            <el-table-column prop="refundAmount" label="退款金额" width="100px">
              <template slot-scope="scope">
                {{ scope.row.refundAmount + '￥' }}
              </template>
            </el-table-column>
            <el-table-column prop="reason" label="退款原因" width="150px"></el-table-column>
            <el-table-column prop="status" label="退款状态" width="100px">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.status === 0" type="warning">待审核</el-tag>
                <el-tag v-if="scope.row.status === 1" type="info">退款中</el-tag>
                <el-tag v-if="scope.row.status === 2" type="success">退款成功</el-tag>
                <el-tag v-if="scope.row.status === 3" type="danger">拒绝</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="refundAt" label="处理时间" width="150px" type="datetime" format="yyyy-MM-dd HH:mm:ss">
              <template slot-scope="scope">
                {{ scope.row.refundAt }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200px">
              <template slot-scope="scope">
                <el-button size="mini" type="primary" @click="handleOrderRefundEdit(scope.$index, scope.row)">查看详情
                </el-button>
                <el-button size="mini" type="danger" @click="handleOrderRefundDelete(scope.$index, scope.row)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <div class="pagination-container">
        <el-pagination
          background
          @size-change="handleSizeChange"
          :page-sizes="pageSizes"
          @current-change="handleCurrentChange"
          :current-page="orderRefundDTO.pageNum"
          :page-size="orderRefundDTO.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
        <el-button class="button_to_page" style="margin-left: 10px" size="small" type="primary" plain @click="toPage">
          跳转
        </el-button>
      </div>
    </div>
  </div>
</template>

<script>
import {
  deleteOrderRefund,
  deleteOrderRefundBatch,
} from '@/api/order/orderRefund'
import { findAll, addOrderRefund } from '@/api/order/orderRefundV2'
import { setRowsByRefundDetail } from '@/utils/auth'

export default {
  name: 'RefundManageV2',
  data() {
    return {
      tableData: [],
      pageSizes: [3, 5, 10, 20],
      editDialogVisible: false,
      multipleSelection: [],
      orderRefund: {
        id: null,
        orderNo: null,
        username: null,
        refundAmount: null,
        reason: null,
        status: null,
        createdAt: null,
        refundAt: null,
      },
      orderRefundDTO: {
        orderId: null,
        userId: null,
        refundAt: null,
        status: null,
        username: null,
        orderNo: null,
        createdAt: null,
        pageNum: 1,
        pageSize: 3
      },
      total: 0,
      editOrderRefundDialog: false,
      rules: {
        orderNo: [
          { required: true, message: '请输入订单号', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ],
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ],
        refundAmount: [
          { required: true, message: '请输入订单总金额', trigger: 'blur' },
          { type: 'number', message: '请输入正确的订单总金额', trigger: 'blur' }
        ],
        reason: [{ required: true, message: '请输入退款原因', trigger: 'blur' }],
        status: [
          { required: true, message: '请选择订单退款状态', trigger: 'blur' }
        ],
        createdAt: [
          { required: true, message: '请选择退款申请时间', trigger: 'blur' }
        ],
        refundAt: [
          { required: true, message: '请选择退款申请时间', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    onSearch() {
      this.findAll()
    },
    findAll() {
      /**格式化日期*/
      const formattedOrderRefundDTO = this.formatOrderRefundDTO(this.orderRefundDTO);
      findAll(formattedOrderRefundDTO).then(res => {
        this.tableData = res.data.list.map(item => {
          this.convertDateFields(item);
          return item;
        });
        this.total = res.data.total
      })
    },
    formatOrderRefundDTO(orderRefundDTO) {
      const formattedOrderRefundDTO = { ...orderRefundDTO };
      if (formattedOrderRefundDTO.createdAt) {
        formattedOrderRefundDTO.createdAt = this.formatDate(formattedOrderRefundDTO.createdAt);
        console.log('格式化后的 createdAt:', formattedOrderRefundDTO.createdAt);
      }
      if (formattedOrderRefundDTO.refundAt) {
        formattedOrderRefundDTO.refundAt = this.formatDate(formattedOrderRefundDTO.refundAt);
        console.log('格式化后的 refundAt:', formattedOrderRefundDTO.refundAt);
      }
      return formattedOrderRefundDTO;
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.orderRefundDTO.pageNum = 1
      this.findAll()
    },
    handleSizeChange(val) {
      this.orderRefundDTO.pageSize = val
      this.findAll()
    },
    handleCurrentChange(val) {
      this.orderRefundDTO.pageNum = val
      this.findAll()
    },
    toPage() {
      this.findAll()
    },
    // 复选框点击事件
    handleSelectionChange(val) {
      this.multipleSelection = []
      for (let i = 0; i < val.length; i++) {
        this.multipleSelection.push(val[i].id)
      }
    },
    // 通过订单id删除订单
    handleOrderRefundDelete(index, row) {
      // 首先要进行弹框提示
      this.$confirm('是否确认删除退款编号为' + '"' + row.id + '"' + '的数据项？', '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const id = row.id
        deleteOrderRefund(id).then((ret) => {
          if (ret.code === 20000) {
            this.$message({
              type: 'success',
              message: '删除成功!',
              duration: 1000
            })
            this.orderRefundDTO.pageNum = 1
            this.findAll()
          } else {
            this.$message({
              type: 'error',
              message: '删除失败',
              duration: 1000
            })
          }
        })
      })
    },
    // 批量删除订单
    deleteOrderRefundBatch() {
      this.$confirm('是否确认删除选中的' + this.multipleSelection.length + '条数据项？', '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteOrderRefundBatch(this.multipleSelection).then((ret) => {
          if (ret.code === 20000) {
            this.$message({
              type: 'success',
              message: '删除成功!',
              duration: 1000
            })
            this.orderRefundDTO.pageNum = 1
            this.findAll()
            // 批量删除成功后，需要清空已选择的行
            this.multipleSelection = []
          } else {
            this.$message({
              type: 'error',
              message: '删除失败',
              duration: 1000
            })
          }
        })
      })
    },
    // 点击修改按钮，触发修改对话框
    handleOrderRefundEdit(index, row) {
      // 点击查询详情按钮会跳转到详情页面
      // 通过编程式路由的方式跳转并且携带参数
      // 先将参数存储到cookie中
      setRowsByRefundDetail({ row: row });
      this.$router.push({ path: '/refund/refundDetail', query: { orderRefund: row } })
    },
    // 添加一个专门处理日期字段的方法--主要解决后端返回的日期格式问题
    convertDateFields() {
      const dateFields = ['createdAt, refundAt']
      dateFields.forEach(field => {
        if (this.orderRefund[field]) {
          this.orderRefund[field] = new Date(this.orderRefund[field])
        }
      })
    },
    // 点击新增按钮，触发新增对话框
    handleAddOrderRefund() {
      this.orderRefund = {}
      this.editDialogVisible = true
      this.$refs.orderRefundDTOForm.resetFields() // 重置表单校验状态
    },

    formatDate(date) {
      if (!date) return null;
      const d = new Date(date);
      const year = d.getFullYear();
      const month = String(d.getMonth() + 1).padStart(2, '0');
      const day = String(d.getDate()).padStart(2, '0');
      const hours = String(d.getHours()).padStart(2, '0');
      const minutes = String(d.getMinutes()).padStart(2, '0');
      const seconds = String(d.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    formatDates(orderRefund) {
      const formattedOrderRefund = { ...orderRefund };
      if (formattedOrderRefund.createdAt) {
        formattedOrderRefund.createdAt = this.formatDate(formattedOrderRefund.createdAt);
        console.log('格式化后的 createdAt:', formattedOrderRefund.createdAt);
      }
      if (formattedOrderRefund.refundAt) {
        formattedOrderRefund.refundAt = this.formatDate(formattedOrderRefund.refundAt);
        console.log('格式化后的 refundAt:', formattedOrderRefund.refundAt);
      }
      return formattedOrderRefund;
    },
    // 点击保存按钮，触发保存事件
    saveOrderRefund(formName) {
      const form = this.$refs[formName];
      if (!form || typeof form.validate !== 'function') {
        console.error('表单组件未正确引用或未实现 validate 方法');
        return false;
      }
      form.validate((valid) => {
        if (valid) {
          const formattedOrderRefund = this.formatDates(this.orderRefund);
            addOrderRefund(formattedOrderRefund).then(ret => {
              if (ret.code === 20000) {
                this.$message({
                  type: 'success',
                  message: '新增成功!',
                  duration: 1000
                })
                this.editDialogVisible = false;
                this.orderRefundDTO.pageNum = 1;
                this.findAll();
                this.resetOrderRefundDTOForm(formName);
              } else {
                this.$message({
                  type: 'error',
                  message: '新增失败!',
                  duration: 1000
                })
              }
            })
        } else {
          this.$message({
            type: 'error',
            message: '表单校验失败!',
            duration: 1000
          })
          return false;
        }
      })
    },
    // 重置表单
    resetOrderRefundDTOForm(formName) {
      // 关闭对话框
      this.editDialogVisible = false
      // 延迟一下，确保表单控件都渲染完毕
      this.$nextTick(() => {
        this.$refs[formName].resetFields() // 重置表单校验状态
      })
    }
  },
  created() {
    this.findAll()
  }
}

</script>

<style scoped>
/* 表格整体样式 */
.orderRefund-table {
  margin-bottom: 20px;
  font-size: 13px;
  border: 1px solid #ebeef5;
}

/* 表头样式 */
.orderRefund-table th {
  background-color: #f5f7fa;
  color: #333;
  font-weight: bold;
  text-align: center;
  white-space: nowrap;
}

/* 单元格样式 */
.el-table td {
  text-align: center;
  padding: 10px 0;
  border-color: #ebeef5;
}

/* 操作按钮的间距调整 */
button.el-button {
  margin: 2px;
  width: 80px; /* 固定按钮宽度 */
}

.pagination-container {
  align-items: center;
  justify-content: center; /* 居中 */
  display: flex; /* 使其成为一个flex容器 */
  margin-top: 10px;
}

.button-container {
  display: flex;
  margin-left: 30px;
  width: 100px;
  background-color: #f5f7fa;
  margin-bottom: 20px;
  margin-top: 20px;
}

.button-container .btn_add {
  margin-right: 10px;
  text-align: center;
  font-size: 16px;
  width: 100px;
  border-top-left-radius: 5px;
}

.button-container .btb_del {
  margin-right: 10px;
  text-align: center;
  font-size: 14px;
  width: 150px;
  border-top-left-radius: 5px;
}

.order-list {
  padding: 0;
}

.order-table {
  margin-top: 20px;
}

/* 标题区域 */
.search-title {
  margin-bottom: 10px; /* 与卡片区域的间距 */
  border: 2px solid red; /* 红色边框 */
  border-radius: 5px; /* 圆角 */
  padding: 5px 10px; /* 内部填充 */
  background-color: #f0f0f0; /* 灰色背景 */
  display: block;
  align-items: center;
}

.title-content {
  display: flex;
  align-items: center;
}

.title-content .el-icon-search {
  font-size: 18px;
  margin-right: 5px; /* 图标与文字间距 */
}

.title-content span {
  font-weight: bold;
  font-size: 16px;
}

/* 卡片区域 */
.box-card {
  border: 1px solid #ebebeb; /* 轻微边框 */
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1); /* 添加阴影 */
  border-radius: 5px; /* 圆角 */
}

.demo-form-inline {
  padding: 10px; /* 内部填充 */
}

/* 表单布局 */
.el-form-item {
  margin-bottom: 15px; /* 表单项间距 */
}

.el-form-item__label {
  width: 80px !important; /* 固定标签宽度 */
  font-weight: bold; /* 加粗标签文字 */
}

.el-form-item__content {
  line-height: 28px; /* 内容垂直居中 */
}

/* 按钮区域 */
.button-group {
  float: right; /* 将按钮区域放在表单右侧 */
}

.el-button {
  margin-left: 10px; /* 按钮间距 */
}

/* 表单整体容器 */
.search-form-container {
  display: flex;
  justify-content: space-between; /* 水平分布 */
  align-items: center; /* 垂直居中 */
}
</style>
